/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/* eslint-disable react/sort-comp */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { debounce, isEmpty } from 'lodash';
import { Card, Row, Col, Form, Select, Button, DatePicker, Spin } from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import InfoCheck from '@/components/InfoCheck';
import router from 'umi/router';
import styles from './style.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';
@connect(({ loading, order, station, user, scanning }) => ({
  station,
  order,
  user,
  scanning,
  stationing: loading.effects['station/getStationList'],
  loading: loading.effects['scanning/getScanningList'],
  operatoring: loading.effects['order/siteOperator'],
}))
@Form.create()
export default class Scanning extends PureComponent {
  state = {
    currentStation: null,
    stationList: [],
  };

  // 翻页
  handleStandardTableChange = debounce(
    pagination => {
      const {
        dispatch,
        scanning: { scanning },
      } = this.props;
      const { formValues } = scanning;
      const params = {
        ...formValues,
        page: pagination.current,
      };
      dispatch({
        type: 'scanning/getScanningList',
        payload: params,
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  // 查询
  handleSearch = debounce(
    e => {
      e && e.preventDefault();
      const {
        dispatch,
        station: { company_info = {} },
      } = this.props;
      this.getFormValues(values => {
        const branch_code =
          values.branch_code == company_info?.brand_code ? 999 : values.branch_code;
        dispatch({
          type: 'scanning/getScanningList',
          payload: {
            ...values,
            cm_code: values.cm_code,
            branch_code,
          },
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  // 业务员列表
  onGetOperatorList = () => {
    const { dispatch, station } = this.props;
    const { company_info = {} } = station;
    const { currentStation } = this.state;
    const { code } = currentStation || { code: '' };
    const site_code = code == company_info?.brand_code ? 999 : code;

    dispatch({
      type: 'order/siteOperator',
      payload: {
        site_code,
      },
    });
  };

  onFilterOperator = (inputValue, options) => {
    const { children, value } = options.props;
    if (children.indexOf(inputValue) >= 0 || value.toString().indexOf(inputValue) >= 0) return true;
  };

  // 站点
  onSelectStation = code => {
    if (!code) return;
    const { currentStation } = this.state;
    if (currentStation && currentStation.code == code) return;
    this.setState({
      currentStation: {
        code,
      },
    });
    const { form } = this.props;
    form.setFieldsValue({
      cm_code: '0',
    });
  };

  // 站点列表
  onGetStationList = () => {
    const { dispatch, station } = this.props;
    dispatch({
      type: 'station/getStationList',
    }).then(() => {
      const { list = [], company_info = {} } = station;
      const stationList = list || [];

      if (!isEmpty(company_info)) {
        stationList.unshift({
          site_code: company_info.brand_code,
          site_name: company_info.brand_name,
        });
      }
      this.setState({
        stationList,
      });
    });
  };

  // 时间格式转换
  getFormValues = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.st_time = start;
        values.end_time = end;
        delete values.date;
      }
      this.setState({
        formValues: values,
      });
      then(values);
    });
  };

  // 导出
  downloadData = () => {
    const {
      form: { getFieldsValue },
    } = this.props;
    const { branch_code, cm_code, date } = getFieldsValue();
    const data = {
      is_export: 'csv',
      cm_code,
      branch_code,
      st_time: moment(date[0]).format(dateFormat),
      end_time: moment(date[1]).format(dateFormat),
    };
    const form = document.createElement('form');
    // 添加到 body 中
    document.body.appendChild(form);
    Object.keys(data).map(item => {
      if (data[item]) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = item;
        input.value = data[item];
        form.appendChild(input);
      }
    });
    form.method = 'POST';
    // form.target = '_blank'
    form.action = '/v1/LocalCity/QueryScanRecord/getRecordTj';
    form.submit();
    document.body.removeChild(form);
  };

  // 扫描统计点击跳转查询页
  scanningQuery = (render, type) => {
    const {
      dispatch,
      form: { getFieldsValue },
    } = this.props;
    const { branch_code, cm_code, date } = getFieldsValue();
    dispatch({
      type: 'global/changeTabActiveKey',
      payload: {
        query: 1,
      },
    });
    dispatch({
      type: 'scanning/getWorkList',
      payload: {
        branch_code: render.branch_code || '',
        cm_code: render.cm_code || '',
        waybill_type: type,
        st_time: moment(date[0]).format(dateFormat),
        end_time: moment(date[1]).format(dateFormat),
      },
    });

    router.push({
      pathname: '../business/query',
      query: {
        // waybillType:type,
        // st_time: moment(date[0]).format(dateFormat),
        // end_time: moment(date[1]).format(dateFormat),
        // branch_code:branch_code||"",
        // cm_code:render.name_code||"",
      },
    });
  };

  handleInfoReady(data) {
    if (!data.name) return;
    this.onGetStationList();
  }

  render() {
    const {
      order,
      scanning: { scanning },
      loading,
      form,
      stationing = false,
      operatoring = false,
      station,
    } = this.props;
    const { stationList } = this.state;
    const { getFieldDecorator } = form;
    const { list, pagination } = scanning;
    const data = { list, pagination };
    const companyInfo = station.company_info || {};
    const operatorList = order.data;
    const columns = [
      {
        title: '站点',
        dataIndex: 'shop_name',
        width: '20%',
        align: 'center',
      },
      {
        title: '业务员',
        dataIndex: 'name_code',
        width: '20%',
        align: 'center',
      },
      {
        title: '收件',
        dataIndex: 'sj',
        width: '20%',
        align: 'center',
        render: (current, currentData) => (
          <a
            onClick={() => {
              this.scanningQuery(currentData, '1');
            }}
          >
            {currentData.sj}
          </a>
        ),
      },
      {
        title: '派件',
        width: '20%',
        align: 'center',
        render: (current, currentData) => (
          <a
            onClick={() => {
              this.scanningQuery(currentData, '2');
            }}
          >
            {currentData.pj}
          </a>
        ),
        dataIndex: 'pj',
      },
      {
        title: '签收',
        width: '20%',
        align: 'center',
        render: (current, currentData) => (
          <a
            onClick={() => {
              this.scanningQuery(currentData, '3');
            }}
          >
            {currentData.qsj}
          </a>
        ),
        dataIndex: 'qsj',
      },
    ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 0 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    // 默认选择时间
    const defaultSelectDate = {
      startDate: moment()
        .startOf('day')
        .subtract(31, 'days'),
      endDate: moment().endOf('day'),
    };
    return (
      <PageHeaderLayout title="扫描记录统计">
        <div className={styles.main}>
          <Card bordered={false} bodyStyle={{ padding: '0 0 24px' }}>
            <Form onSubmit={this.handleSearch} className={styles['search-form']}>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={9} sm={24}>
                  <FormItem {...formItemLayout} label="扫描上传时间">
                    {getFieldDecorator('date', {
                      initialValue: [defaultSelectDate.startDate, defaultSelectDate.endDate],
                    })(
                      <RangePicker
                        style={{ width: '100%' }}
                        placeholder={['开始日期', '结束日期']}
                      />,
                    )}
                  </FormItem>
                </Col>
                <Col md={9} sm={24}>
                  <FormItem label="公司站点" {...formItemLayout}>
                    {getFieldDecorator('branch_code')(
                      <Select
                        onFocus={this.onGetStationList}
                        onSelect={this.onSelectStation}
                        placeholder="请选择公司站点"
                        allowClear
                      >
                        {stationing ? (
                          <Option disabled value="loading">
                            <Spin />
                          </Option>
                        ) : (
                          <Option key="all" value="0">
                            全部站点
                          </Option>
                        )}
                        {stationList.map(({ site_code, site_name }) => (
                          <Option
                            key={site_code}
                            value={
                              companyInfo.brand_code === site_code
                                ? site_code
                                : companyInfo.brand_code + site_code
                            }
                          >
                            {site_name}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={9} sm={24}>
                  <FormItem {...formItemLayout} label="业务员">
                    {getFieldDecorator('cm_code')(
                      <Select
                        onFocus={this.onGetOperatorList}
                        filterOption={this.onFilterOperator}
                        onPopupScroll={this.onScrollOperator}
                        showSearch
                        allowClear
                        placeholder="请输入姓名或者工号"
                      >
                        {operatoring ? (
                          <Option disabled value="loading">
                            <Spin />
                          </Option>
                        ) : (
                          <Option key="all" value="0">
                            全部业务员
                          </Option>
                        )}
                        {operatorList.map(({ courier_no, courier_name }) => (
                          <Option key={courier_no} value={courier_no}>
                            {courier_name}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
                <Col md={9} sm={24} />
                <Col md={6} sm={24}>
                  <span className={styles.submitButtons}>
                    <Button
                      type="primary"
                      htmlType="submit"
                      key="search"
                      icon="search"
                      loading={loading}
                    >
                      查询
                    </Button>
                  </span>
                </Col>
              </Row>
            </Form>
          </Card>
          <div style={{ paddingBottom: '24px' }}>
            <Button
              type="primary"
              icon="download"
              onClick={() => {
                this.downloadData();
              }}
            >
              导出
            </Button>
          </div>
          <StandardTable
            rowKey="waybill_no"
            loading={loading}
            data={data}
            columns={columns}
            onChange={this.handleStandardTableChange}
          />
        </div>
        <InfoCheck onReady={this.handleInfoReady.bind(this)} />
      </PageHeaderLayout>
    );
  }
}
